package org.yty.travelagencymongodb.service.impl;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.yty.travelagencymongodb.model.Entity.TourGroup;
import org.yty.travelagencymongodb.repository.TourGroupRepository;
import org.yty.travelagencymongodb.service.SignUpService;
import org.yty.travelagencymongodb.service.TourGroupService;
import org.yty.travelagencymongodb.service.TourGroupTravellerService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class TourGroupServiceImpl implements TourGroupService {
    private final TourGroupRepository tourGroupRepository;
    private final MongoTemplate mongoTemplate;
    @Lazy
    @Autowired
    private TourGroupTravellerService tourGroupTravellerService;
    @Lazy
    @Autowired
    private SignUpService signUpService;

    @Override
    public TourGroup getById(Long id) {
        Optional<TourGroup> option = this.tourGroupRepository.findById(id);
        return option.isEmpty() ? null : option.get();
    }

    @Override
    public boolean save(TourGroup tourGroup) {
        if (tourGroup.getId() == null){
            tourGroup.setId(IdUtil.getSnowflakeNextId());
        }
        tourGroup.setCreateTime(LocalDateTime.now());
        tourGroup.setUpdateTime(LocalDateTime.now());
        tourGroup = this.tourGroupRepository.insert(tourGroup);
        return tourGroup != null;
    }

    @Override
    public boolean update(TourGroup tourGroup) {
        tourGroup.setUpdateTime(LocalDateTime.now());
        tourGroup = this.tourGroupRepository.save(tourGroup);
        return tourGroup != null;
    }

    @Override
    public void removeById(Long id) {
        this.tourGroupTravellerService.deleteByTourGroupId(id);
        this.signUpService.deleteByTourGroupId(id);
        this.tourGroupRepository.deleteById(id);
    }

    @Override
    public List<TourGroup> getListByIdList(List<Long> tourGroupIdList) {
        Criteria queryCriteria = Criteria.where("id").in(tourGroupIdList);
        return this.mongoTemplate.find(new Query(), TourGroup.class);
    }
}
